package jk.framework.spring.security.authentication;


import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author cuichao
 */
public class AuthenticationDetailsProvider extends DaoAuthenticationProvider {

    private UserDetailsPasswordService userDetailsPasswordService;
    private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();

    public AuthenticationDetailsProvider(UserDetailsService service) {
        setUserDetailsService(service);
    }

    @Override
    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {

        boolean upgradeEncoding = this.userDetailsPasswordService != null
                && getPasswordEncoder().upgradeEncoding(user.getPassword());
        if (upgradeEncoding) {
            String presentedPassword = authentication.getCredentials().toString();
            String newPassword = getPasswordEncoder().encode(presentedPassword);
            user = this.userDetailsPasswordService.updatePassword(user, newPassword);
        }

        AuthenticationDetailsToken result = new AuthenticationDetailsToken(principal, authentication.getCredentials(),
                authoritiesMapper.mapAuthorities(user.getAuthorities()));
        result.setDetails(authentication.getDetails());
        result.setUserDetails(user);
        return result;

    }


    @Override
    public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
        super.setAuthoritiesMapper(authoritiesMapper);
        this.authoritiesMapper = authoritiesMapper;
    }

    @Override
    public void setUserDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService) {
        super.setUserDetailsPasswordService(userDetailsPasswordService);
        this.userDetailsPasswordService = userDetailsPasswordService;
    }
}
